package com.hzncc.scaffold.controller.Front.Lecture;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzncc.scaffold.config.MinioConfig;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Other.Lecture;
import com.hzncc.scaffold.entity.Other.Userlecture;
import com.hzncc.scaffold.entity.Other.Usertag;
import com.hzncc.scaffold.entity.Vo.LectureDetailVo;
import com.hzncc.scaffold.entity.Vo.LectureIdVo;
import com.hzncc.scaffold.entity.Vo.SearchLectureVo;
import com.hzncc.scaffold.entity.Vo.UserIdVo;
import com.hzncc.scaffold.service.LectureService;
import com.hzncc.scaffold.service.UserService;
import com.hzncc.scaffold.service.UserlectureService;
import com.hzncc.scaffold.service.UsertagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: DrunkBear
 * @Date: 2022-06-08 11:01
 * @Description: null
 */
@Api(tags = "前台接口-名师讲堂")
@RequestMapping("/lecture")
@RestController
public class LectureController {

    @Autowired
    LectureService lectureService;

    @Autowired
    UserlectureService userlectureService;

    @Autowired
    UserService userService;

    @Autowired
    UsertagService usertagService;
    
    @Autowired
    MinioConfig minioConfig;

    @Value("${project.imgFileSuffix}")
    public String imgFileSuffix;



    @GetMapping("/search")
    @ApiOperation("名师讲堂列表")
    public ResultT search(Integer pageNum, Integer pageSize, String sort, String keyword) {

        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        LambdaQueryWrapper<Lecture> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotEmpty(keyword), Lecture::getTitle, keyword);
        lqw.orderByDesc("DESC".equals(sort), Lecture::getStartTime);
        lqw.orderByAsc("Asc".equals(sort), Lecture::getStartTime);

        List<Lecture> lectureList = lectureService.list(lqw);

        List<SearchLectureVo> searchLectureVos = BeanUtil.copyToList(lectureList, SearchLectureVo.class);

        //判断用户是否加入课程
        for (SearchLectureVo searchLectureVo : searchLectureVos) {

            searchLectureVo.setCover(imgFileSuffix+ searchLectureVo.getCover());

            if (StpUtil.isLogin()) {
                int userId = StpUtil.getLoginIdAsInt();
                LambdaQueryWrapper<Userlecture> lqww = new LambdaQueryWrapper<>();
                lqww.eq(Userlecture::getUserId, userId);
                lqww.eq(Userlecture::getLectureId, searchLectureVo.getId());

                if (CollUtil.isEmpty(userlectureService.list(lqww))) {
                    searchLectureVo.setJoined(false);
                } else {
                    searchLectureVo.setJoined(true);
                }
            }
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",searchLectureVos);
        map.put("count",new PageInfo<>(lectureList).getTotal());
//        PageInfo<SearchLectureVo> info = new PageInfo<>();
//        info.setList(searchLectureVos);
//        info.setTotal(new PageInfo<>(lectureList).getTotal());

        return ResultT.success(map);
    }


    @GetMapping("/detail")
    @ApiOperation("名师讲堂详细信息")
    public ResultT detail(Integer lectureId) {
        if (lectureService.getById(lectureId) == null) {
            return ResultT.fail("数据错误");
        }

        Lecture lecture = lectureService.getById(lectureId);
        LectureDetailVo lectureDetailVo = BeanUtil.toBean(lecture, LectureDetailVo.class);

        LambdaQueryWrapper<Userlecture> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Userlecture::getLectureId, lectureId);
        List<Userlecture> userlectures = userlectureService.list(lqw);
        List<Integer> userIdList = userlectures.stream().map(Userlecture::getUserId).collect(Collectors.toList());

        ArrayList<UserIdVo> users = new ArrayList<>();

        for (Integer userId : userIdList) {
            UserIdVo userIdVo = new UserIdVo();
            userIdVo.setUserId(userId);

            users.add(userIdVo);
        }

        //判断用户是否加入课程
        if (StpUtil.isLogin()) {
            int userId = StpUtil.getLoginIdAsInt();
            LambdaQueryWrapper<Userlecture> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Userlecture::getUserId, userId);
            lqww.eq(Userlecture::getLectureId, lectureId);

            if (CollUtil.isEmpty(userlectureService.list(lqww))) {
                lectureDetailVo.setJoined(false);
            } else {
                lectureDetailVo.setJoined(true);
            }
        }
        lectureDetailVo.setCover(imgFileSuffix+lectureDetailVo.getCover());
        lectureDetailVo.setUsers(users);
        return ResultT.success(lectureDetailVo);
    }

    @PostMapping("/join")
    @ApiOperation("加入名师讲堂")
    public ResultT join(@RequestBody LectureIdVo lectureIdVo) {

        Integer lectureId = lectureIdVo.getLectureId();

        if (!StpUtil.isLogin()) {
            return ResultT.fail("您未登录");
        }
        if (lectureService.getById(lectureId) == null) {
            return ResultT.fail("数据错误");
        }

        int userId = StpUtil.getLoginIdAsInt();
        if (userService.getById(userId) == null) {
            return ResultT.fail("数据错误");
        }
        LambdaQueryWrapper<Usertag> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Usertag::getUserId, userId);
        if (CollUtil.isEmpty(usertagService.list(lqw))) {
            return ResultT.fail("您没有权限，请先开通权限");
        }
        List<Integer> tagList = usertagService.list(lqw).stream().map(Usertag::getTagId).collect(Collectors.toList());
        List<Integer> authentationList = StrUtil.split(lectureService.getById(lectureId).getAuthentation(), ",").stream().map(Integer::parseInt).collect(Collectors.toList());

        if (!CollUtil.containsAny(authentationList, tagList)) {
            return ResultT.fail("您没有权限，请先开通权限");
        }

        Userlecture userlecture = new Userlecture();
        userlecture.setUserId(userId);
        userlecture.setLectureId(lectureId);

        LambdaQueryWrapper<Userlecture> lqww = new LambdaQueryWrapper<>();
        lqww.eq(Userlecture::getUserId, userId);
        lqww.eq(Userlecture::getLectureId, lectureId);
        if (CollUtil.isNotEmpty(userlectureService.list(lqww))) {
            return ResultT.fail("您已报名该课程");
        }

        boolean save = userlectureService.save(userlecture);
        if (save) {
            return ResultT.success("加入成功");
        } else {
            return ResultT.fail("加入失败");
        }
    }
}
